<template>
	<view class="">
		<heade title="下单" :fanStatus="false" bg_color="bg_fff"></heade>
		<view class="">
			<!-- <view class="bg_fff p-t10 p-b15">
				<view class="headeClass  co_fff f-s20 f-w600 d-flex align-center justify-content-center">您本月还未产生销售，加油哟！</view>
			</view> -->
			<view class="">
				<!-- 常用功能 -->
				<view class="bg_fff p-b20  box_box m-t12 m-l12 m-r12 border-r10">
					<view class="f-s15 p-t20 p-l15">常用功能</view>
					<view class="d-flex align-center m-t20">
						<view class="text-center" style="width: 33.33%;" v-for="(item,i) in commonly" @tap="$common.url(item.url)">
							<text :class="[item.icon,i == 0?'f-s28':'f-s22']" class="iconfont " :style="{'color': item.color}"></text>
							<view class="f-s14 m-t8">{{item.name}}</view>
						</view>
					</view>
				</view>
				<!-- 全部列表 -->
				<view class="bg_fff p-b20  box_box m-t12 m-l12 m-r12 border-r10">
					<view class="f-s15 p-t20 p-l15">全部列表</view>
					<view class="d-flex align-center m-t20">
						<view class="text-center" style="width: 33.33%;" v-for="(item,i) in wholeList" @tap="$common.url(item.url)">
							<text :class="[item.icon,i == 2?'f-s22':'f-s28']" class="iconfont " :style="{'color': item.color}"></text>
							<view class="f-s14 m-t8">{{item.name}}</view>
						</view>
					</view>
				</view>
				<!-- 常用设置 -->
				<view class="bg_fff p-b20  box_box m-t12 m-l12 m-r12 border-r10">
					<view class="f-s15 p-t20 p-l15">常用设置</view>
					<view class="d-flex align-center m-t20">
						<view class="text-center" style="width: 33.33%;" v-for="(item,i) in setUpList" @tap="urlLink(item)">
							<text :class="[item.icon]" class="iconfont f-s24" :style="{'color': item.color}"></text>
							<view class="f-s14 m-t8">{{item.name}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="text-center f-s14 co_999 dinbu">
			<view class="m-t14">当前版本号：{{version}}</view>
			<!-- <view class="m-t8">咨询服务：073184161520</view> -->
		</view>
	</view>
</template>

<script>
	import {
		openComDB,
		executeSQL,
		dropSQL
	} from '@/common/sqlite.js';
	export default {
		data() {
			return {
				index:0,
				commonly:[
					{name:'销售订单',icon:'icon-xiaoshoudingdan',color:'#ff5c5f',url:'/pages/parameters/parameters?title=销售订单'},
					{name:'销货单',icon:'icon-xierushujuku',color:'#fe8f28',url:'/pages/parameters/parameters?title=销货单'},
					{name:'退货单',icon:'icon-tuihuodan',color:'#fe8f28',url:'/pages/parameters/parameters?title=退货单'},
				],
				wholeList:[
					{name:'销售订单列表',icon:'icon-dingdan',color:'#33b0fa',url:'/pages/salesOrderList/salesOrderList'},
					{name:'销货单列表',icon:'icon-dingdanguanli',color:'#33b0fa',url:'/pages/salesOrderList/salesList'},
					{name:'草稿列表',icon:'icon-caogaoxiang',color:'#06b447',url:'/pages/aDraftList/aDraftList'},
				],
				setUpList:[
					{name:'设置',icon:'icon-shezhi',color:'#33b0fa',url:'/pages/home/setUp'},
					{name:'更新数据',icon:'icon-shujubiangeng',color:'#33b0fa'},
					// {name:'云打印设置',icon:'icon-yundayin',color:'#fd5e63'},
				],
				backButtonPress:0,
				InventoryPrice:[],
				InventoryUnit:[],
				InventoryQueryV2:[],
				CurrentStock:[],
				// #ifdef APP-PLUS
				number:10000, 
				// #endif
				// #ifdef H5
				number:2000,
				// #endif
				classQueryNum:1,
				usersListNum:1,
				orderNum:1,
				departmentNum:1,
				OryUnitNum:1,
				version:'1.0.0'
			}
		}, 
		onLoad: function(option) {
			plus.runtime.getProperty(plus.runtime.appid, (info) => {
				 this.version = info.version;
			   // this.versionCode = info.versionCode ;
			}) 
			uni.$sql.connect({
			    name: 'xiaoap',// 数据库名称
			    path:'_doc/xiaoap.db', // 路径
			});
			executeSQL('xiaoap', `select count(1) from 'theCustomer1'`, res => {
				if(res.length > 0) {
					console.log(res.length) 
				}else {
					if(this.$db.get('token')) {
						this.getWarehouse()
					}
				}
				
			})
		},
		methods: { 
			urlLink(item) {
				if(item.name == '更新数据') {
					this.getWarehouse()
					// this.getorder()
					// this.getDepartment()
				}else {
					this.$common.url(item.url)
				}
			},
			// 获取仓库列表
			getWarehouse() {
				uni.showLoading({
					title: '正在同步数据',
					mask:true 
				});
				this.$http.post('ApiAS/WarehouseQuery',{ "param": {}},true).then(res => {
					if(res.statusCode = 200) {
						// this.$db.set('warehouse',JSON.parse(res.data))
						this.dbInit(JSON.parse(res.data));
					}else{
						uni.showToast({title:'同步失败，获取仓库列表出错',icon:'none'})
						uni.hideLoading();
					}
				})
			}, 
			// 获取仓库列表
			dbInit: function(data) {
				let _this = this
				let studentModel = uni.$sql.model('warehouse',{
				    'ID':String,
					'Name':String,
					'Code':String,
				});
				let arr = [];
				for (var i = 0; i < data.length; i++) {
				    arr.push({ 'ID': data[i].ID, 'Name': data[i].Name,'Code': data[i].Code})
				}
				studentModel.sql('delete from warehouse',(err,results)=>{
					studentModel.insert(arr, (err, results, option, index) => {
						if(_this.classQueryNum == 1) {
							_this.classQueryNum++
							_this.getClassQuery()
						}
					}); 
				});
				
			},
			// 获取用户分类
			getClassQuery() {
				this.$http.post('ApiAS/PartnerClassQuery',{param:{}},true).then(res => {
					if(res.statusCode == 200) {
						this.dbClassQuery(res.data)
					}else{
						uni.showToast({title:'同步失败，获取用户分类出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			dbClassQuery: function(data) {
				//获取用户分类；
				let _this = this
				let num = 1
				let studentModel = uni.$sql.model('kehuList_1',{
				    'id':String,
					'code':String,
					'name':String,
					'parentCode':String,
					'depth':String,
					'isEndNode':String,
					'ts':String,
					'sub':String,
				});
				let arr = [];
				for (var i = 0; i < data.length; i++) {
				    arr.push({ 
						'id': data[i].id, 
						'code': data[i].code,
						'name': data[i].name, 
						'parentCode': data[i].parentCode,
						'depth': data[i].depth,
						'isEndNode': data[i].isEndNode,
						'ts': data[i].ts,
						'sub':JSON.stringify(data[i].sub),
					})
				}
				studentModel.sql('delete from kehuList_1',(err,results)=>{
					studentModel.insert(arr, (err, results, option, index) => {
						if(_this.usersListNum == 1) {
							_this.usersListNum++
							_this.getUsersList()
						}
					}); 
				});
			},
			// 获取用户列表
			getUsersList() {
				let resData = {
					param:{
						"pageSize":Number(this.number + '0'),
						"pageIndex": 1,
						ts:''
					} 
				}
				this.$http.post('ApiAS/PartnerQueryV2',resData,true).then(res => {
					if(res.statusCode == 200) {
						this.dbUsersList(res.data)
					}else{
						uni.showToast({title:'同步失败，获取用户列表出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			dbUsersList: function(data) {
				//获取用户列表；
				let _this = this
				let studentModel = uni.$sql.model('theCustomer1',{
				    'id':String,
					'code':String,
					'partnerType':String,
					'partnerClass':String,
					'settlementPartner':String,
					'saleDepartment':String,
					'saleMan':String,
					'district':String,
					'priceGrade':String,
					'createdTime':String,
					'madeRecordDate':String,
					'disabled':String,
					'creditBalance':String,
					'saleCreditLine':String,
					'arBalance':String,
					'advRBalance':String,
					'apBalance':String,
					'advPBalance':String,
					'ts':String,
					'representative':String,
					'customerAddressPhone':String,
					'partnerAddresDTOs':String,
					'priuserdefdecm6':String,
					'name':String, 
				});
				let arr = [];
				for (var i = 0; i < data.length; i++) {
				    arr.push({ 
						'id': data[i].id, 
						'code':data[i].code,
						'partnerType':JSON.stringify(data[i].partnerType),
						'partnerClass':JSON.stringify(data[i].partnerClass),
						'settlementPartner':JSON.stringify(data[i].settlementPartner),
						'saleDepartment':JSON.stringify(data[i].saleDepartment),
						'saleMan':data[i].saleMan,
						'district':data[i].district,
						'priceGrade':JSON.stringify(data[i].priceGrade),
						'createdTime':data[i].createdTime,
						'madeRecordDate':data[i].madeRecordDate,
						'disabled':data[i].disabled,
						'creditBalance':data[i].creditBalance,
						'saleCreditLine':data[i].saleCreditLine,
						'arBalance':data[i].arBalance,
						'advRBalance':data[i].advRBalance,
						'apBalance':data[i].apBalance,
						'advPBalance':data[i].advPBalance,
						'ts':data[i].ts,
						'representative':data[i].representative,
						'customerAddressPhone':data[i].customerAddressPhone,
						'partnerAddresDTOs':JSON.stringify(data[i].partnerAddresDTOs),
						'priuserdefdecm6':data[i].priuserdefdecm6,
						'name':data[i].name || '',
					})
				}
				studentModel.sql('delete from theCustomer1',(err,results)=>{
					studentModel.insert(arr, (err, results, option, index) => {
						 if(_this.orderNum == 1) {
							_this.orderNum++
							_this.getorder()
						 }
					}); 
				});
			},
			// 获取商品分类
			getorder() {
				this.$http.post('ApiAS/InventoryClassQuery',{"param": {}},true).then(res => {
					if(res.statusCode == 200) {
						// this.$db.set('goodsList',res.data)
						this.dbClassification(res.data)
					}else{
						uni.showToast({title:'同步失败，获取商品分类出错',icon:'none'})
						uni.hideLoading();
					}
				}) 
			},
			dbClassification(data) {
				//获取商品分类；
				let _this = this
				let studentModel = uni.$sql.model('goodsList2',{
				    'id':String,
					'code':String,
					'name':String,
					'parentCode':String,
					'depth':String,
					'isEndNode':String,
					'ts':String,
					'sub':String,
				});
				let arr = [];
				for (var i = 0; i < data.length; i++) {
				    arr.push({ 
						'id': data[i].id, 
						'code': data[i].code,
						'name': data[i].name, 
						'parentCode': data[i].parentCode,
						'depth': data[i].depth,
						'isEndNode': data[i].isEndNode,
						'ts': data[i].ts,
						'sub':JSON.stringify(data[i].sub),
					})
				}
				studentModel.sql('delete from goodsList2',(err,results)=>{
					studentModel.insert(arr, (err, results, option, index) => {
						if(_this.departmentNum == 1) {
							_this.departmentNum++ 
							_this.getDepartment()
						}
					}); 
				});
			},
			// 获取商品现存量
			getDepartment() {
				// uni.showLoading({
				// 	title: '正在同步数据',
				// 	mask:true 
				// });
				this.$http.post('ApiST/CurrentStock',{param: {"pageSize": Number(this.number + '0')}},true).then(res => {
					if(res.statusCode == 200) {
						this.CurrentStock = res.data
						this.getData()
					}else{
						console.log(555)
						uni.showToast({title:'同步失败，获取商品现存量出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			// 获取商品列表
			getData() {
				let resData = {
					param:{
						"pageSize": this.number,
						"pageIndex": 1,
						ts:''
					}
				}
				this.$http.post('ApiAS/InventoryQueryV2',resData,true).then(res => {
					if(res.statusCode == 200) {
						this.InventoryQueryV2 = JSON.parse(res.data)
						console.log(JSON.parse(res.data).length)
						this.getConfig()
					}else if(!res){
						console.log(666)
						uni.showToast({title:'同步失败，获取商品列表出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			// 查询存货价格本
			getConfig(){
				this.$http.post('ApiAS/InventoryPrice',{ "ts": 0,"pageSize":Number(this.number + '0')},true).then(res => {
					if(res.statusCode == 200) {
						this.InventoryPrice = res.data
						// console.log(res.data[0])
						this.getOryUnit()
					}else{
						uni.showToast({title:'同步失败，获取存货价格本出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			// 查询存货计量单位
			getOryUnit(){
				let _this = this
				this.$http.post('ApiAS/InventoryUnit',{ "ts": 0,"pageSize": Number(this.number + '0')},true).then( res => {
					if(res.statusCode == 200) {
						let list = []
						this.InventoryUnit = res.data
						res.data.forEach((q,k) => {
							if(q.unitName == '中组') {
								res.data.splice(k,1)
							}
						})
						res.data.forEach((j,i) => {
							_this.InventoryPrice.forEach((t,index) => {
								if(j.invCode == t.invCode && j.unitID == t.idunit) {
									list.push({
										"id":t.id,
										"UnitCode":j.invCode || '',
										"UnitName": j.unitName || '',
										"RetailPriceNew":t.retailPriceNew || '',
										Price:t.retailPrice,
										PriceObj:t
									})
								}
							})
						})
						let list2 = [];
						let value = [];
						let Existing = [];
						_this.InventoryQueryV2.forEach(e => {
							this.CurrentStock.forEach((o,index) => {
								if(e.Code == o.inventoryCode) {
									Existing.push(o)
									e.ExistingQuantityList = Existing
									if(o.warehouseName == '主仓') {
										e.ExistingQuantity = o.existingQuantity
									}
								}else {
									Existing = []
								}
							})
							
							list.forEach(k => {
								if(e.Code == k.UnitCode) {
									if(k.UnitName.indexOf('袋') != -1 || k.UnitName.indexOf('kg') != -1 || k.UnitName.indexOf('盒') != -1 || k.UnitName.indexOf('个') != -1 || k.UnitName.indexOf('包') != -1){
										list2.unshift(k)
									}else {
										list2.push(k)
									}
									e.partnerUnitPrice = list2
									if(list2.length == 2) {
										list2 = []
									}
								}
							})
							e.isStatus = false;
							e.checked = false;
							e.number = 0;
							e.giftChecked = false;
							if(e.partnerUnitPrice) {
								if(e.partnerUnitPrice[0]) {
									e.partnerUnitPrice.forEach((j,index) => {
										j.count = false
									})
									e.RetailPriceNew = e.partnerUnitPrice[0].RetailPriceNew
									if(this.$db.get('default_config').unit == 2) {
										e.partnerUnitPrice[1].count = true
									}else {
										e.partnerUnitPrice[0].count = true
									}
									
									e.Price = e.partnerUnitPrice[0].Price
									e.UnitName = e.partnerUnitPrice[0].UnitName
								}
							}
						})
						this.dbOryUnit(_this.InventoryQueryV2)
					}else{
						console.log(888)
						uni.showToast({title:'同步失败，获取存货计量单位出错',icon:'none'})
						uni.hideLoading();
					}
				})
			},
			dbOryUnit: function(data) {
				//查询存货计量单位；
				let _this = this
				let studentModel = uni.$sql.model('commodity2',{
					'ExistingQuantityList':String,
					'ExistingQuantity':Number,
				    'Price':String,
					'RetailPriceNew':String,
					'UnitName':String,
					'checked':String,
					'code':String,
					'defaultBarCode':String,
					'disabled':String,
					'giftChecked':String,
					'id':String,
					'inventoryClass':String,
					'isStatus':String,
					'name':String,
					'number':String,
					'partnerUnitPrice':String,
					'priuserdefdecm1':String,
					'priuserdefdecm6':String,
					'priuserdefdecm7':String,
					'priuserdefnvc1':String,
					'priuserdefnvc2':String,
					'priuserdefnvc4':String,
					'productInfo':String,
					'shorthand':String,
					'specification':String,
					'ts':String, 
				});
				let arr = [];
				let ExistingQuantity_demo = 0
				for (var i = 0; i < data.length; i++) {
					if(data[i].ExistingQuantity && data[i].ExistingQuantity != 'undefined') {
						let value = []
						value = data[i].ExistingQuantity.split('.')
						ExistingQuantity_demo = value[0]
					}else {
						ExistingQuantity_demo = 0
					}
				    arr.push({ 
						'ExistingQuantityList':JSON.stringify(data[i].ExistingQuantityList) || '',
						'ExistingQuantity':ExistingQuantity_demo || 0.00,
						'Price':data[i].Price,
						'RetailPriceNew':data[i].RetailPriceNew,
						'UnitName':data[i].UnitName,
						'checked':data[i].checked,
						'code':data[i].Code,
						'defaultBarCode':data[i].DefaultBarCode,
						'disabled':data[i].Disabled,
						'giftChecked':data[i].giftChecked,
						'id':data[i].ID,
						'inventoryClass':JSON.stringify(data[i].InventoryClass),
						'isStatus':data[i].isStatus,
						'name':data[i].Name,
						'number':data[i].number,
						'partnerUnitPrice':JSON.stringify(data[i].partnerUnitPrice),
						'priuserdefdecm1':data[i].priuserdefdecm1,
						'priuserdefdecm6':data[i].priuserdefdecm6,
						'priuserdefdecm7':data[i].priuserdefdecm7,
						'priuserdefnvc1':data[i].priuserdefnvc1,
						'priuserdefnvc2':data[i].priuserdefnvc2,
						'priuserdefnvc4':data[i].priuserdefnvc4,
						'productInfo':JSON.stringify(data[i].ProductInfo),
						'shorthand':data[i].Shorthand,
						'specification':data[i].Specification,
						'ts':data[i].Ts,
					})
				}
				studentModel.sql('delete from commodity2',(err,results)=>{
					studentModel.insert(arr, (err, results, option, index) => {
							 _this.OryUnitNum++
						 if(_this.OryUnitNum == data.length) {
							uni.hideLoading();
							this.$common.show('同步成功')
						 }
					}); 
				});
			},
		}
	}
</script>

<style>
	page {
		background: #f3f2f7;
	}
</style>
<style lang="scss">
	.headeClass{
		width: 710rpx;
		height: 190rpx;
		background-color: #4095ff;
		border-radius: 20rpx;
		margin: 0 auto;
	}
	.dinbu{
		position: absolute;
		bottom: 40rpx;
		width: 100%;
		text-align: center;
	}
</style>
